/*******************************************************************************
 * Copyright (c) 2011 Olexandr V. Shaposhnikov.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Olexandr V. Shaposhnikov - initial API and implementation and/or initial documentation
 *******************************************************************************/
package com.funkyroach.use.udk;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.core.IStreamListener;
import org.eclipse.debug.core.Launch;
import org.eclipse.debug.core.model.IStreamMonitor;
import org.eclipse.debug.core.model.RuntimeProcess;

import com.funkyroach.use.plugin.USPlugin;

public class USUDKLauncher implements IStreamListener {

    private StringBuffer result;
    private String udkHome;
    private String udkBinFolder;

    public USUDKLauncher(String udkHome, String udkBinFolder) {
        this.udkHome = udkHome;
        this.udkBinFolder = udkBinFolder;
    }

    public int runUDKexe(StringBuffer sb, String... params) {
        result = sb;
        List<String> commandLine = new ArrayList<String>();
        String command = udkHome + udkBinFolder + "udk.com";
        commandLine.add(command);
        for (String param : params) {
            commandLine.add(param);
        }
        ProcessBuilder pb = new ProcessBuilder(commandLine);
        pb.directory(new File(udkHome));
        try {
            Process process = pb.start();
            ILaunch launch = new Launch(null, ILaunchManager.RUN_MODE, null);
            RuntimeProcess runtimeProcess = new RuntimeProcess(launch, process, "udk", null);
            IStreamMonitor monitor = runtimeProcess.getStreamsProxy().getOutputStreamMonitor();
            monitor.addListener(this);
            while (!runtimeProcess.isTerminated()) {
                Thread.sleep(10);
            }
            return runtimeProcess.getExitValue();
        } catch (IOException e) {
            USPlugin.log(e);
        } catch (InterruptedException e) {
            USPlugin.log(e);
        } catch (DebugException e) {
            USPlugin.log(e);
        }
        return -1;
    }

    public void streamAppended(String text, IStreamMonitor monitor) {
        result.append(text);
    }

}
